package com.k2data.app.k2bq.skylar360.utils;

import org.apache.commons.codec.binary.Base64;
import com.k2data.app.k2bq.skylar360.utils.exception.DecryptException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Arrays;

public class DecryptAES {
    private static final Charset ASCII = Charset.forName("US-ASCII");

    public static String decryptAES(String base64Cipher) throws DecryptException {
        try {
            String aeskey = "aes_key_16_bytes";
            byte[] cipherBytes = Base64.decodeBase64(base64Cipher);
            byte[] iv = aeskey.getBytes(ASCII);
            byte[] keyBytes = aeskey.getBytes(ASCII);
            SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
            byte[] result = cipher.doFinal(cipherBytes);
            return new String(Arrays.copyOfRange(result, 16, result.length));
        } catch (Exception e) {
            throw new DecryptException("decryptAES error");
        }
    }
}